package com.powermgr.boringtest.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.powermgr.boringtest.result.Result;
import com.powermgr.boringtest.service.IPrService;
import com.powermgr.boringtest.utils.InitUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * PrServiceImpl
 *
 * @author qiuxiangdong
 * @date 2023/6/12
 */
@Log4j2
@Service
public class PrServiceImpl implements IPrService {
    @Override
    public Result<Object> getPrTag(String prUrl) {
        try{
            String s = urlRegex(prUrl);
            String api = "https://gitee.com/api/v5/repos/" + s
                    + "?access_token=" + InitUtils.getUserValue("gitee_token");
            return Result.success("success",getInfo(api));
        } catch (Exception E){
            log.error("*获取pr标签时失败");
            return Result.failure("获取pr标签时失败",null);
        }
    }
    @Override
    public Result<Object> getPrVersion(String prBranch, String prUrl) {
        try{
            String api = getApi(prUrl);
            if(api == null){
                return Result.failure("获取pr评论时失败",null);
            }
            return getDayu200_version(prBranch,JSONArray.parseArray(getInfo(api)));
        } catch (Exception E){
            log.error("*获取pr评论时失败");
            return Result.failure("获取pr评论时失败",null);
        }
    }
    @Override
    public Result<Object> getPrTdd(String prBranch, String prUrl) {
        try{
            String api = getApi(prUrl);
            if(api == null){
                return Result.failure("获取pr评论时失败",null);
            }
            return getDayu200_tdd(prBranch,JSONArray.parseArray(getInfo(api)));
        } catch (Exception E){
            log.error("*获取pr评论时失败");
            return Result.failure("获取pr评论时失败",null);
        }
    }
    @Override
    public Result<Object> getPrXts(String prBranch, String prUrl) {
        try{
            String api = getApi(prUrl);
            if(api == null){
                return Result.failure("获取pr评论时失败",null);
            }
            return getDayu200_xts(prBranch,JSONArray.parseArray(getInfo(api)));
        } catch (Exception E){
            log.error("*获取pr评论时失败");
            return Result.failure("获取pr评论时失败",null);
        }
    }
    private String getApi(String prUrl) {
        try{
            return "https://gitee.com/api/v5/repos/" + urlRegex(prUrl) + "/comments?access_token="
                    + InitUtils.getUserValue("gitee_token")
                    + "&page=1&per_page=30&direction=desc&comment_type=pr_comment";
        } catch (Exception E){
            log.error("*获取pr评论时失败");
            return null;
        }
    }
    private String urlRegex(String info) {
        String result = "";
        Pattern r = Pattern.compile("openharmony*.*");
        Matcher m = r.matcher(info);
        if (m.find()) {
            result = m.group(0);
        } else {
            log.error("*无法截取字符串");
        }
        return result;
    }
    private String getInfo(String prUrl) {
        HttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(prUrl);
        try {
            HttpResponse res = client.execute(httpGet);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(res.getEntity());
            }
        } catch (Exception e) {
            log.error("*服务无法链接到");
            return null;
        }
        return null;
    }
    private Result<Object> getDayu200_version(String prBranch, JSONArray jsonArray) {
        return getDayu200(prBranch,jsonArray, "version",true);
    }
    private Result<Object> getDayu200_tdd(String prBranch, JSONArray jsonArray) {
        return getDayu200(prBranch,jsonArray, "tdd",false);
    }
    private Result<Object> getDayu200_xts(String prBranch, JSONArray jsonArray) {
        return getDayu200(prBranch,jsonArray, "xts",false);
    }
    private Result<Object> getDayu200(String prBranch, JSONArray jsonArray,String caseType ,boolean isVersion) {
        if (prBranch.contains("weekly")){
            prBranch = "weekly";
        }
        if (prBranch.contains("monthly")){
            prBranch = "monthly";
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            try{
                String body = (String) jsonArray.getJSONObject(i).get("body");
                if (body.contains("代码门禁未通过") || body.contains("代码门禁通过")){
                    String result = "";
                    Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*(\"|\')?(.*?)[\"|\'|>]", Pattern.CASE_INSENSITIVE);
                    Matcher m = p.matcher(body);
                    while (m.find()) {
                        String link = m.group(2).trim();
                        String name = InitUtils.getCiValue(prBranch,caseType);
                        if (link.contains(name)) {
                            result = link;
                        }
                        if (result.contains("tar.gz")){
                            return Result.success("success", result);
                        }
                    }
                }
            }catch (IndexOutOfBoundsException e){
                log.error("*IndexOutOfBoundsException",e);
            }
        }
        if (isVersion){
            log.error("*在评论中没有找到下载版本地址");
            return Result.failure("在评论中没有找到下载版本地址，请检查。","existence");
        } else {
            return Result.success("在评论中没有找到测试用例下载地址。","existence");
        }
    }
}
